package com.neo.common.base;


import com.neo.common.utils.jedis.JedisClient;
import com.neo.config.exception.BasicException;
import com.neo.config.exception.BusinessException;
import com.neo.config.exception.ParameterException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 */
public class Base2Controller {
    @Autowired
    public JedisClient jedisClient;
    public boolean isEnabled(String userId, String token) {

        boolean flag = true;
        System.out.println(AppConstants.USER_PRE + userId);
        if (jedisClient.get(AppConstants.USER_PRE + userId).equals(token)) {
            flag = false;
        }
        return flag;
    }
    /**
     * 指定异常全局处理
     *
     * @param request
     * @param response
     * @param exception
     * @return
     */

    @ExceptionHandler(value = BasicException.class)
    public Map<String, Object> errorHandler(HttpServletRequest request, HttpServletResponse response, BasicException
            exception) {
        String message = exception.getMessage();
        int code = 500;
        if (exception instanceof ParameterException) {
            code = 400;
        }
        if (exception instanceof BusinessException) {
            code = 501;
        }
//        response.setStatus(code);
        return fail(message);
    }

    protected Map<String, Object> sucess() {
        return BaseCode.jsonString("成功", AppConstants.OK);
    }

    protected Map<String, Object> sucess(Object data) {
        return BaseCode.jsonString("成功", data, AppConstants.OK);
    }

    protected Map<String, Object> fail() {
        return BaseCode.jsonString("失败", AppConstants.FAIL);
    }

    /**
     * 自定义失败消息
     *
     * @param message
     * @return
     */
    protected Map<String, Object> fail(String message) {
        return BaseCode.jsonString(message, AppConstants.FAIL);
    }

    /**
     * 自定义失败状态
     *
     * @param status
     * @return
     */
    protected Map<String, Object> fail(int status) {
        return BaseCode.jsonString("失败", status);
    }

    /**
     * 自定义失败状态，失败消息
     *
     * @param status
     * @param message
     * @return
     */
    protected Map<String, Object> fail(int status, String message) {
        return BaseCode.jsonString(message, status);
    }



    /**
     * 自定义成功状态，成功消息
     *
     * @param status
     * @param message
     * @return  data
     */
    protected Map<String, Object> sucess(int status, Object data,String message) {
        return BaseCode.jsonString(message, data,status);
    }


    /**
     * 自定义失败状态，登录信息失效
     *
     * @return data
     */
    protected Map<String, Object> tokenFail() {
        return BaseCode.jsonString("登录信息已失效，请重新登录", AppConstants.USER_LOGIN_ERR);
    }


}
